//
//  SearchViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/12.
//

import UIKit

class SearchViewController: BaseViewController {
    var searchTextField: UITextField!
    var tableView: BaseTableView!
    var historySearchArray  = NSMutableArray()//历史搜索记录
    var selectParam = SelectparameterModel()  //选中的参数：比如 车型，多个车型逗号拼接
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.view.backgroundColor = UIColor(hex: 0xF8F9FA)
        self.initSearchView()
        self.initTableView()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getHistorySearchData()
    }
    
   
    func initSearchView() {
        
        let searchView = UIView(frame: CGRect(x: 54, y: NavBarHight - 39, width: kScreenWidth - 130, height: 32))
        searchView.backgroundColor = .white
        searchView.layer.cornerRadius = 16
        searchView.clipsToBounds = true
        searchView.layer.borderWidth = 1.5
        searchView.layer.borderColor = UIColor(hex: 0x222222).cgColor
        self.navBar.addSubview(searchView)
        
        let imageSearch = UIImageView(frame: CGRect(x: 13, y: 9, width: 14, height: 14))
        imageSearch.image = UIImage(named: "icon_search")
        searchView.addSubview(imageSearch)
        
        self.searchTextField = UITextField.init(frame: CGRect(x:imageSearch.right + 10, y: 0, width: searchView.width - 50, height: 32))
        self.searchTextField.textColor = Theme.titleLabColor
        self.searchTextField.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        self.searchTextField.placeholder = MMLocalizedString("search_vehicle", comment: "搜索车辆")
        self.searchTextField.returnKeyType = .search
        self.searchTextField.keyboardType = .default
        self.searchTextField.clearButtonMode = .always
        self.searchTextField.delegate = self
        self.searchTextField.addTarget(self , action: #selector(self.textFieldChanged(textField:)), for: UIControlEvents.editingChanged)
        searchView.addSubview(self.searchTextField)
        
        let searchBtn = UIButton(frame: .zero)
        searchBtn.setTitle(MMLocalizedString("search", comment: "搜索"), for: .normal)
        searchBtn.setTitleColor(Theme.mainColor, for: .normal)
        searchBtn.addTarget(self, action: #selector(confirmSearchBtnAction), for: .touchUpInside)
        searchBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.navBar.addSubview(searchBtn)
        
        searchBtn.snp.makeConstraints { make in
            make.right.equalTo(-14)
            make.height.width.equalTo(44)
            make.bottom.equalTo(0)
        }
    
    }
    
    //tableView
    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - TabbarHeight), style: .grouped)
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 100
        self.tableView.register(HistorySearchTableViewCell.self, forCellReuseIdentifier: "HistorySearchTableViewCell")
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = UIColor(hex: 0xF8F9FA)
        self.tableView.keyboardDismissMode = .onDrag
        self.view.addSubview(self.tableView)
    }
    
    //获取历史搜索数据
    func getHistorySearchData(){
        let historySearchData = LLKeyValueStore.share()?.getAllItems(fromTable: XTManageCenter.SearchHistoryTable)
        if historySearchData != nil{
            self.historySearchArray.removeAllObjects()
            if historySearchData?.count ?? 0 > 0{
                for kk in (0...(historySearchData?.count ?? 0)-1).reversed()  {
                    let tempItem = historySearchData![kk] as! YTKKeyValueItem
                    self.historySearchArray.add(tempItem.itemId)
                }
            }
            self.tableView.reloadData()
        }
    }
    
    
    //MARK： - Aation
    @objc func textFieldChanged(textField: UITextField){
        printLog(textField.text)
        if textField.text == "" {
            //说明为空
            self.tableView.reloadData()
        }else{
        }
    }
    
    ///确定搜索
    @objc func confirmSearchBtnAction(){
        if self.searchTextField.text?.count == 0{
            self.view.makeToast(message:MMLocalizedString("keyword_search", comment: "请输入搜索车辆"))
        }else{
                LLKeyValueStore.share()?.put(self.searchTextField.text ?? "", withId: self.searchTextField.text ?? "", intoTable: XTManageCenter.SearchHistoryTable)
                let vc = SearchResultViewController()
                vc.selectParam = self.selectParam//选中的参数：比如 车型，多个车型逗号拼接
                vc.searchText = self.searchTextField.text ?? ""
                self.navigationController?.pushViewController(vc, animated: true)
        }
    }

}


extension SearchViewController: UITextFieldDelegate{
    func textFieldDidBeginEditing(_ textField: UITextField) {
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "\n" {
            if textField.text != "" {
            }
            self.confirmSearchBtnAction()
        }
        return true
    }
}

extension SearchViewController: UITableViewDelegate,UITableViewDataSource{
    
  
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HistorySearchTableViewCell", for: indexPath) as! HistorySearchTableViewCell
        cell.setHistoryData(data: self.historySearchArray)
        cell.delegate = self
        return cell
     
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if self.historySearchArray.count == 0 && section == 0{
            return 0.01
        }
        return 60
    
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 60))
        headerView.clipsToBounds = true
        headerView.backgroundColor = UIColor(hex: 0xF8F9FA)
        let titleLab = UILabel(frame: CGRect(x: 20, y: 0, width: kScreenWidth - 40, height: 60))
        titleLab.textColor = Theme.titleLabColor
        titleLab.textAlignment = .left
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        headerView.addSubview(titleLab)
        let clearRecordBtn = UIButton(frame: CGRect(x: kScreenWidth - 54 , y: 0, width: 40, height: 60))
        clearRecordBtn.contentHorizontalAlignment = .right
        
        titleLab.text = MMLocalizedString("search_history", comment: "历史搜索")
        clearRecordBtn.setImage(UIImage(named: "icon_delete_search"), for: .normal)
        clearRecordBtn.setImage(UIImage(named: "icon_delete_search"), for: .highlighted)
        clearRecordBtn.setTitleColor(Theme.mainColor, for: .normal)
        clearRecordBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        
        headerView.addSubview(clearRecordBtn)
        clearRecordBtn.addTargetUsingBlock {[weak self] btn in
            self?.alertView()
        }
        if self.historySearchArray.count == 0{
            headerView.height = 0.01
            titleLab.height = 0.01
            clearRecordBtn.height = 0.01
            clearRecordBtn.isHidden = true
        }else{
            headerView.height = 60
            titleLab.height = 60
            clearRecordBtn.height = 60
            clearRecordBtn.isHidden = false
        }
    return headerView
}
    
    func alertView(){
        XTAlertView.showAlertView(title: nil,
                                  message: MMLocalizedString("clear_search_content", comment: "清空历史搜索记录?"),
                                  cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                  otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")]) { alert, tag in
            if tag == 1 {
                //确定
                LLKeyValueStore.share()?.clearDB(withTableName: XTManageCenter.SearchHistoryTable)
                self.historySearchArray.removeAllObjects()
                self.tableView.reloadData()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        footerView.backgroundColor = .white
        return footerView
    }
    
    
    //记录搜索内容
    func recordSearchContent(content: String){
        LLKeyValueStore.share()?.put(content, withId: content, intoTable: XTManageCenter.SearchHistoryTable)
    }
    
}

/// 选择搜索历史记录
extension SearchViewController: HistorySearchDelegate{
    func didSelectSearchHistoryItem(index: NSInteger, tagTitle: String) {
        self.recordSearchContent(content: tagTitle)
        let vc = SearchResultViewController()
        vc.selectParam = self.selectParam//选中的参数：比如 车型，多个车型逗号拼接
        vc.searchText = tagTitle
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
